﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using EventFlowLibrary.GameStructure;
using System.IO;

namespace ScreenManagement
{
    class StartScreen : MenuScreen
    {
        Texture2D startButton;

        /// <summary>
        /// Load settings on first update
        /// </summary>
        bool settingsLoaded = false;

        #region Initialization

        /// <summary>
        /// Constructor fills in the menu contents.
        /// </summary>
        public StartScreen()
            : base("")
        {
            // Create a hidden menu entry to get the active user controller index
            MenuEntry hitStartButton = new MenuEntry("");

            // Hook up menu event handlers.
            hitStartButton.Selected += startButtonSelected;

            // Add entries to the menu.
            MenuEntries.Add(hitStartButton);
        }

        public override void LoadContent()
        {
            ContentManager content = ScreenManager.Game.Content;

            startButton = content.Load<Texture2D>("Textures/Buttons/xboxControllerStart");

            base.LoadContent();

            // Start music
            Microsoft.Xna.Framework.Media.MediaPlayer.Play(AudioManager.backgroundMusic[0]);
            Microsoft.Xna.Framework.Media.MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(AudioManager.MediaPlayer_MediaStateChanged);
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            // Try to load existing settings. Give slight pause, added for testing, just so we can load without having to go through intro screen.
            if (!settingsLoaded)// && startMilliseconds > 100)
            {
                try
                {
                    if (this.ScreenManager.SaveDevice.IsReady)
                    {
                        // Turn on Async if we want
                        this.ScreenManager.SaveDevice.LoadAsync("MurderForDinner_Settings", "_settings",
                            stream =>
                            {
                                try
                                {
                                    using (BinaryReader reader = new BinaryReader(stream))
                                    {
                                        this.ScreenManager.gameSettings.MusicVolume = (float)reader.ReadDouble();           // Load the music volume
                                        this.ScreenManager.gameSettings.SoundEffectVolume = (float)reader.ReadDouble();     // Load the sound volume
                                        this.ScreenManager.gameSettings.Inverted = reader.ReadBoolean();                    // Load inverted
                                        this.ScreenManager.gameSettings.CameraBobEnabled = reader.ReadBoolean();             // Load camera bob
                                    }
                                }
                                catch
                                {
                                    //MessageBoxScreen confirmExitMessageBox = new MessageBoxScreen(new string[] { "Save device is not ready. Please retry." }, true, false, true, true);
                                    //confirmExitMessageBox.Accepted += OnCancel;
                                    //ScreenManager.AddScreen(confirmExitMessageBox, this.ControllingPlayer.Value);
                                }
                            });
                    }
                    else
                    {
                        MessageBoxScreen confirmExitMessageBox = new MessageBoxScreen(new string[] { "Save device is not ready. Could not load options." }, true, false, true, true);
                        confirmExitMessageBox.Accepted += OnCancel;
                        ScreenManager.AddScreen(confirmExitMessageBox, this.ControllingPlayer.Value);
                    }
                }
                catch
                {
                    //MessageBoxScreen confirmExitMessageBox = new MessageBoxScreen(new string[] { "Save device is not ready. Could not load options." }, true, false, true, true);
                    //confirmExitMessageBox.Accepted += OnCancel;
                    //ScreenManager.AddScreen(confirmExitMessageBox, this.ControllingPlayer.Value);
                }

                settingsLoaded = true;
            }

            if (IsActive)
            {
                //fadeTimer += gameTime.ElapsedGameTime.Milliseconds;

                //if (fadeTimer > timeToShow)
                //{
                //    this.ScreenManager.AddScreen(new MainMenuScreen(), null);
                //    this.ScreenManager.RemoveScreen(this);
                //}
            }

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        public override void Draw(GameTime gameTime)
        {
            ScreenManager.SpriteBatch.Begin();
            
            ScreenManager.SpriteBatch.Draw(startButton, new Vector2((ScreenManager.GraphicsDevice.Viewport.Width / 2) - (startButton.Width / 2), ((ScreenManager.GraphicsDevice.Viewport.Height / 3) * 2) - (startButton.Height / 2)), Color.White);

            ScreenManager.SpriteBatch.End();

            base.Draw(gameTime);
        }

        #endregion

        #region Handle Input

        /// <summary>
        /// When the user cancels the main menu, ask if they want to exit the sample.
        /// </summary>
        protected override void OnCancel(PlayerIndex playerIndex)
        {
            MessageBoxScreen confirmExitMessageBox = new MessageBoxScreen(new string[] { "Are you sure you want to exit this game?" }, true, true, true, true);

            confirmExitMessageBox.Accepted += ConfirmExitMessageBoxAccepted;

            ScreenManager.AddScreen(confirmExitMessageBox, playerIndex);
        }

        /// <summary>
        /// Event handler for when the user selects ok on the "are you sure
        /// you want to exit" message box.
        /// </summary>
        void ConfirmExitMessageBoxAccepted(object sender, PlayerIndexEventArgs e)
        {
            ScreenManager.Game.Exit();
        }

        /// <summary>
        /// Event handler for when the Play Game menu entry is selected.
        /// </summary>
        void startButtonSelected(object sender, PlayerIndexEventArgs e)
        {
            GlobalVariables.playerIndex = e.PlayerIndex;
            switch (e.PlayerIndex)
            {
                case PlayerIndex.One:
                    GlobalVariables.playerIndexInt = 0;
                    break;
                case PlayerIndex.Two:
                    GlobalVariables.playerIndexInt = 1;
                    break;
                case PlayerIndex.Three:
                    GlobalVariables.playerIndexInt = 2;
                    break;
                case PlayerIndex.Four:
                    GlobalVariables.playerIndexInt = 3;
                    break;
            }
            //GlobalVariables.playerIndex = Convert.ToInt32(e.PlayerIndex.ToString());
            this.ScreenManager.AddScreen(new MainMenuScreen(), e.PlayerIndex);
            this.ScreenManager.RemoveScreen(this);
        }

        #endregion
    }
}
